import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:in_app_review/in_app_review.dart';
import 'app_color.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'common/api_service.dart'; // 导入 ApiService 类
import 'ads/app_open_ad_manager.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'ads/app_lifecycle_reactor.dart';
import 'ads/consent_manager.dart';
import 'tab.dart';
import 'package:firebase_core/firebase_core.dart';

// MembershipProvider 类
// class MembershipProvider with ChangeNotifier {
//   bool _isMember = false;
//   DateTime? _expiryDate; // 过期时间戳

//   bool get isMember => _isMember;
//   DateTime? get expiryDate => _expiryDate;

//   void setMember(bool value, {DateTime? expiryDate}) {
//     _isMember = value;
//     _expiryDate = expiryDate;
//     notifyListeners();
//   }

//   void checkMembershipStatus() {
//     if (_expiryDate != null && DateTime.now().isAfter(_expiryDate!)) {
//       _isMember = false;
//       _expiryDate = null; // 可选：重置过期时间
//       notifyListeners();
//     }
//   }
// }

void main() async{
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    // options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
  
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        scaffoldBackgroundColor: Colors.white,
        appBarTheme: const AppBarTheme(
          backgroundColor: Colors.white, // 设置AppBar背景颜色为白色
          titleTextStyle: TextStyle(
            color: Colors.black, // 设置标题字体颜色为黑色
            fontSize: 20, // 可选：设置字体大小
          ),
          iconTheme: IconThemeData(
            color: Colors.black, // 设置图标颜色为黑色
          ),
        ),
      ),
      // home: const MyHomePage(index: 0),
      home: const StartPage(),
    );
  }
}

class StartPage extends StatefulWidget {
  const StartPage({super.key});

  @override
  State<StartPage> createState() => _StartPageState();
}

class _StartPageState extends State<StartPage> {
  int vip = 0;
  final _appOpenAdManager = AppOpenAdManager();
  // final _consentManager = ConsentManager.instance;
  var _isMobileAdsInitializeCalled = false;
  var _isPrivacyOptionsRequired = false;
  late AppLifecycleReactor _appLifecycleReactor;


  // 检查网络
  List<ConnectivityResult> _connectionStatus = [ConnectivityResult.none];
  final Connectivity _connectivity = Connectivity();
  late StreamSubscription<List<ConnectivityResult>> _connectivitySubscription;

  bool isLoading = false;

  Future<void> _loadVipStatus() async {
      _appLifecycleReactor =
        AppLifecycleReactor(appOpenAdManager: _appOpenAdManager);
      _appLifecycleReactor.listenToAppStateChanges();
      
      ConsentManager.instance.gatherConsent((consentGatheringError) {
        if (consentGatheringError != null) {
          // Consent not obtained in current session.
          debugPrint(
              "${consentGatheringError.errorCode}: ${consentGatheringError.message}");
        }

        // Check if a privacy options entry point is required.
        _getIsPrivacyOptionsRequired();

        // Attempt to initialize the Mobile Ads SDK.
        _initializeMobileAdsSDK();
      });

      // This sample attempts to load ads using consent obtained in the previous session.
      _initializeMobileAdsSDK();
  }

  @override
  void initState() {
    super.initState();
    initConnectivity();

    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);

    _loadVipStatus();

  }

  /// Redraw the app bar actions if a privacy options entry point is required.
  void _getIsPrivacyOptionsRequired() async {
    if (await ConsentManager.instance.isPrivacyOptionsRequired()) {
      setState(() {
        _isPrivacyOptionsRequired = true;
      });
    }
  }

  /// Initialize the Mobile Ads SDK if the SDK has gathered consent aligned with
  /// the app's configured messages.
  void _initializeMobileAdsSDK() async {
    if (_isMobileAdsInitializeCalled) {
      return;
    }

    if (await ConsentManager.instance.canRequestAds()) {
      _isMobileAdsInitializeCalled = true;

      // Initialize the Mobile Ads SDK.
      MobileAds.instance.initialize();

      // // Load an ad.
      _appOpenAdManager.loadAd();
    }
  }

  Future<void> initConnectivity() async {
    late List<ConnectivityResult> result;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      // developer.log('Couldn\'t check connectivity status', error: e);
      return;
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) {
      return Future.value(null);
    }

    return _updateConnectionStatus(result);
  }

  Future<void> _updateConnectionStatus(List<ConnectivityResult> result) async {
    setState(() {
      _connectionStatus = result;
    });
    if(result != [ConnectivityResult.none]){
      print('网络状态已更新');
      fetchData();
      // Load an ad.
      // _appOpenAdManager.loadAd();
    }
    // ignore: avoid_print
    print('Connectivity changed: $_connectionStatus');
  }

  void fetchData() async {
    print('发起请求');
    setState(() {
      isLoading = true;
    });
    try {
      String url = 'https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/json/ads16.json'; // 替换为你的 URL
      List<dynamic> jsonData = await ApiService.fetchJsonData(url);
      // print(jsonData);

      final prefs = await SharedPreferences.getInstance();
      prefs.setInt('bannerAdStatus', jsonData[0]['ad']['ios']['banner']);
      prefs.setInt('inlineAdStatus', jsonData[0]['ad']['ios']['inline_banner']);
      prefs.setInt('insertAdStatus', jsonData[0]['ad']['ios']['interstitial']);
      prefs.setInt('rewardAdStatus', jsonData[0]['ad']['ios']['reward']);

      // prefs.setInt('bannerAdStatus', 1);
      // prefs.setInt('inlineAdStatus', 1);
      // prefs.setInt('insertAdStatus', 1);
      // prefs.setInt('rewardAdStatus', 1);
      // print('-----');
      print(jsonData[0]['ad']['ios']);

      setState(() {
        // isTryAgain = false;
        isLoading = false;
        // categoryList = jsonData[0]['list'];
        // trendData = jsonData[0]['trend'];
      });
      // getFavoriteList();
      // _loadAd();
    } catch (e) {
      setState(() {
        isLoading = false;
      });
    }
  }


  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    return Scaffold(
      body: SafeArea(
        child: Container(
          width: width,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const Spacer(),
              ClipRRect(
                borderRadius: BorderRadius.circular(24),
                child: Image.asset('images/icon.png', width: 120, height: 120,),
              ),
              const SizedBox(height: 16,),
              const Text('Buenos días', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),),
              
              const Spacer(),

              isLoading ? Container(
                height: 56,
                margin: const EdgeInsets.only(bottom: 120),
                child: const Center(
                  child:  CircularProgressIndicator(backgroundColor: Colors.white, color: AppColors.primary,),
                ),
              )  :
              Container(
                margin: const EdgeInsets.only(left: 24, right: 24, bottom: 120),
                child: InkWell(
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const MyHomePage(initialIndex: 0,),
                      ),
                    );
                    
                  },
                  child: Container(
                    height: 56,
                    
                    decoration: BoxDecoration(
                      color: AppColors.primary,
                      borderRadius: BorderRadius.circular(28)
                    ),
                    child: const Center(
                      child: Text('CONTINUAR', style: TextStyle(color: Colors.white, fontSize: 20),),
                    ) ,
                  ),
                ) ,
              )
              
            ],
          ),
        ) 
      )
    );
  }
}


